// pages/all/all.js
const db = wx.cloud.database()
const _ = db.command
const col = "resources"

// 在页面中定义激励视频广告
let videoAd = null
let isSerach = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    isEndOfList: false,
    limit: 20, //每次拉取数量
    inputVal: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.getData()
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      // 加载激励视频广告
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-221500b8a3a3a2d6'
      })
      //捕捉错误
      videoAd.onError(err => {
        console.log(err)
        // 进行适当的提示
      })
      // 监听关闭
      videoAd.onClose((status) => {
        if (status && status.isEnded || status === undefined) {
          // 正常播放结束，下发奖励
          // continue you code
          if (isSerach == true) {
            wx.navigateTo({
              url: '/pages/search/search?value=' + that.data.inputVal,
            })
            isSerach = false
          }
        } else {
          // 播放中途退出，进行提示 
          // console.log(that.data.inputVal)
        }
      })
    }
  },

  getData: function () {
    db.collection(col)
      // .where({
      //   classify: 2
      // })
      // .orderBy('click', 'desc')
      .skip(this.data.list.length)
      .limit(this.data.limit)
      .get()
      .then(res => {
        this.setData({
          list: [...this.data.list, ...res.data], //合并数据
          isEndOfList: res.data.length < this.data.limit ? true : false //判断是否结束
        })
      })
      .catch(err => {
        wx.showToast({ title: '加载失败', mask: true, icon: 'error' })
        console.error('getStudyData()：', err)
      })
  },

  otherBottom: function () {
    !this.data.isEndOfList && this.getData()
  },

  // 查询
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  searchData: function () {
    isSerach = true
    let value = this.data.inputVal
    if (value) {
      // 用户触发广告后，显示激励视频广告
      if (videoAd) {
        videoAd.show().catch(() => {
          // 失败重试
          videoAd.load()
            .then(() => {
              videoAd.show()
            })
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
      }
    }
  },
  clearInput: function () {
    this.setData({
      inputVal: "",
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value,
    });
  },

  // 告诉管理员资源失效
  handleLongPress(e) {
    wx.showModal({
      title: '提示',
      content: '是否告诉管理员该资源已失效？',
      // confirmText: '确认',
      success: ({ confirm }) => {
        if (confirm) {
          const { id } = e.currentTarget.dataset
          db.collection('resources').doc(id).update({
            data: {
              failure: true
            },
            success: function (res) {
              console.log(res)
            },
            fail: function (res) {
              console.log('资源失效:', res)
            }
          })
        }
      },
    })
  },
  onCopyTap(e) {
    const { data, id, idx } = e.currentTarget.dataset
    let that = this
    db.collection(col).doc(id).update({
      data: {
        click: _.inc(1)
      },
      success: function (res) {
        let newData = that.data.list
        newData[idx].click += 1
        that.setData({
          list: newData
        })
      },
      fail: function (res) {
        console.log('点击自增失败:', res)
      }
    })
    wx.setClipboardData({
      data,
      success: () => {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
})